package com.example.controller;

import com.example.model.Bill;
import com.example.model.BillItem;
import com.example.model.Customer;
import com.example.service.DiscountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sun.nio.cs.ext.Big5_HKSCS;

import java.math.BigDecimal;
import java.util.List;

@RestController
public class DiscountController {

    @Autowired
    private DiscountService discountService;

    @GetMapping("/hello")
    public String hello(){
        return "Hello";
    }

    @GetMapping("/getCustomer")
    public Customer getCustomer(@RequestParam String idCard){
        Customer customer = discountService.getCustomer(idCard);
        if (customer==null){
            return new Customer();
        }
        return customer;
    }

    @GetMapping(value = "/getVipLevel",
            consumes = MediaType.APPLICATION_ATOM_XML_VALUE,
            produces = MediaType.APPLICATION_ATOM_XML_VALUE)
    public String getVipLevel(@RequestParam String idCard){
        //获取customer信息
        Customer customer = discountService.getCustomer(idCard);
        //判断VIP等级
        if (customer.getVipType()==null){
            return "非VIP用户";
        }else{
            return customer.getVipType();
        }

    }

    @GetMapping("/discount")
    public String getDiscount(@RequestParam String itemName,
                              @RequestParam String vipLevel,
                              @RequestParam BigDecimal price){
        try {
            BigDecimal currentPrice = discountService.discount(vipLevel,itemName,price);
            return currentPrice.toString();
        }catch (Exception e){
            e.printStackTrace();
            return "Error";
        }
    }
    @GetMapping("/bills")
    public List<Bill> getBills(@RequestParam Long customerId){
        return discountService.findBillsByCustomerId(customerId);
    }

    @PostMapping("/bill")
    public Bill postBill(@RequestParam Bill bill) throws Exception {
        System.out.println(bill);
        Long customerId= bill.getCustomerId();
        Customer customer = discountService.getCustomer(customerId);
        String vipType = customer.getVipType();
        BigDecimal totalPrice = BigDecimal.valueOf(0);
        for (BillItem billItem : bill.getBillItemList()){
            BigDecimal discountPrice = discountService.discount(vipType,billItem.getItemName(),billItem.getPrice());
            billItem.setDiscountedPrice(discountPrice);
            totalPrice = totalPrice.add(discountPrice);
        }
        bill.setTotal_price(totalPrice);
        return bill;
    }
}
